package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class ServiceItemImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private ICarPackageAuditService carPackageAuditService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IBpmnInfoService bpmnInfoService;


    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        //页面收集的数据并不完整， 需要额外维护
        //创建时间
        serviceItem.setCreateTime(new Date());
        // 审核状态：重要的状态明确设置
        // 必须是套餐才审核（不是套餐不需要审核）
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            //套餐， 需要审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }else{
            // 非套餐， 不审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        //上架状态--默认是非上架
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        // 根据id去查询出，在数据库中的所有数据
        ServiceItem oldObject = serviceItemMapper.selectByPrimaryKey(serviceItem.getId());
        if (oldObject==null) {
            throw new BusinessException("参数异常");
        }
        // 上架不能修改
        if (ServiceItem.SALESTATUS_ON.equals(oldObject.getSaleStatus())) {
            throw new BusinessException("项目上架不能修改");
        }
        // 审核中不能被修改
        if (ServiceItem.AUDITSTATUS_AUDITING.equals(oldObject.getAuditStatus())) {
            throw new BusinessException("审核中不能被修改");
        }
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public void delete(Long id) {
        serviceItemMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    // 上架
    @Override
    public void saleOn(Long id) {
        //满足什么条件才允许上架(通过id能查出和商品还没上架)
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        if (serviceItem ==null || ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())) {
            throw new BusinessException("非法参数或者该商品已上架");
        }

        //普通服务单项---直接上架(不是套餐)
        if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())) {
            serviceItemMapper.changeSaleStatus(ServiceItem.SALESTATUS_ON,id);
        }else{
            // 是套餐
            if (ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())) {
                serviceItemMapper.changeSaleStatus(ServiceItem.SALESTATUS_ON,id);
            }else{
                throw new BusinessException("需要审核通过状态才可以上架");
            }
        }
    }



    // 下架
    @Override
    public void saleOff(Long id) {
        //满足什么条件才允许下架(通过id能查出和商品已经上架)
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        if (serviceItem ==null || ServiceItem.SALESTATUS_OFF.equals(serviceItem.getSaleStatus())) {
            throw new BusinessException("非法参数或者该商品下架");
        }
        serviceItemMapper.changeSaleStatus(ServiceItem.SALESTATUS_OFF,id);
    }


    @Override
    public void startAudit(Long serviceItemId, Long bpmnInfoId, Long director, Long finance, String info) {
       // 根据传入的id查询服务项，服务项状态处于初始化才能惊醒审核逻辑
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(serviceItemId);
        if (serviceItem==null || !ServiceItem.AUDITSTATUS_INIT.equals(serviceItem.getAuditStatus())) {
            throw new BusinessException("参数异常");
        }

        //修改服务状态，修改为审核中
        serviceItemMapper.changeAuditStatus(serviceItemId,ServiceItem.AUDITSTATUS_AUDITING);
        // 审核信息记录
        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemId(serviceItemId);
        audit.setServiceItemInfo(serviceItem.getInfo());
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        audit.setCreateTime(new Date());
        audit.setCreator(ShiroUtils.getUser().getUserName());
        audit.setBpmnInfoId(bpmnInfoId);
        audit.setInfo(info);
        audit.setAuditorId(director);
        carPackageAuditService.save(audit);
        // 启动流程实例，以金额作为实例参数
        HashMap<String, Object> map = new HashMap<>();
        if (director !=null) {
            map.put("director",director.toString());
        }
        if (finance !=null) {
            map.put("finance",finance.toString());
        }
        map.put("discountPrice",serviceItem.getDiscountPrice().longValue());
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        // 启动流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(bpmnInfo.getActProcessKey(),
                audit.getId().toString(), map);

        // 更新记录实例id
        audit.setInstanceId(processInstance.getId());
        carPackageAuditService.updateInstanceId(audit);
    }

    @Override
    public void changeAuditStatus(Long serviceItemId, Integer auditStatus) {
        serviceItemMapper.changeAuditStatus(serviceItemId,auditStatus);
    }


}
